package com.xyg.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.xyg.pojo.Result;
import com.xyg.pojo.User;
import com.xyg.response.LoginResponse;
import com.xyg.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping( "/api/auth" )
public class AuthController {

    private final UserService userService;

    @Autowired
    public AuthController ( UserService userService ) {
        this.userService = userService;
    }

    //* 用户注册: /api/auth/register
    @PostMapping( "/register" )
    public Result< User > register ( @RequestBody User user ) {
        if ( user == null || user.getUsername() == null || user.getPassword() == null ) {
            return Result.failure( 400, "用户名和密码不能为空" );
        }
        User registeredUser = userService.save( user );
        return Result.success( "注册用户成功", registeredUser );
    }

    //* 用户登录: /api/auth/login
    @PostMapping( "/login" )
    public Result< LoginResponse > login ( @RequestBody User user ) {
        if ( user == null || user.getUsername() == null || user.getPassword() == null ) {
            return Result.failure( 400, "用户名和密码不能为空" );
        }
        if ( userService.authenticate( user ) ) {
            StpUtil.login( user.getUsername() );
            User loggedInUser = userService.findByUsername( user.getUsername() ).get();
            LoginResponse response = new LoginResponse( "登录成功", StpUtil.getTokenValue(), loggedInUser );
            return Result.success( response );
        }
        return Result.failure( 401, "用户名或密码错误" );
    }

    //* 退出登录: /api/auth/logout
    @GetMapping( "/logout" )
    public Result< Void > logout () {
        StpUtil.logout();
        return Result.success( "退出成功", null );
    }

}
